import os
from tkinter import Tk, simpledialog, filedialog, Toplevel, Label

def search_files_by_keyword(directory, keyword, max_depth, update_label):
    matching_files = []
    for root, dirs, files in os.walk(directory):
        # Calculate the current depth
        depth = root[len(directory):].count(os.sep)
        if depth > max_depth:
            # Skip deeper directories but ensure current files are processed
            dirs[:] = []
        # Process all files in the current directory
        for file in files:
            current_file = os.path.join(root, file)
            # Debug print for each file being checked
            print(f"正在检索文件: {current_file}")
            # Update the label with the current file being checked
            update_label(f"正在检索文件: {current_file}")
            if keyword.lower() in file.lower():
                matching_files.append(current_file)
    return matching_files

def main():
    # Hide the root Tkinter window
    root = Tk()
    root.withdraw()

    print("请选择一个文件夹进行搜索...")
    selected_directory = filedialog.askdirectory(title="选择文件夹")

    if not selected_directory:
        print("未选择文件夹，程序退出。")
        return

    # Use a dialog to input the keyword
    keyword = simpledialog.askstring("输入关键字", "请输入搜索关键字:")
    if not keyword:
        print("未输入关键字，程序退出。")
        return

    # Use a dialog to input the maximum depth
    max_depth = simpledialog.askinteger("输入搜索层数", "请输入搜索的文件层数 (0 表示仅当前目录):", minvalue=0)
    if max_depth is None:
        print("未输入搜索层数，程序退出。")
        return

    # Create a new window to display the current file being checked
    progress_window = Toplevel()
    progress_window.title("搜索进度")
    progress_label = Label(progress_window, text="正在准备搜索...")
    progress_label.pack(padx=20, pady=20)

    def update_label(text):
        progress_label.config(text=text)
        progress_window.update()

    print(f"正在搜索包含关键字 '{keyword}' 的文件，搜索层数为 {max_depth}...")
    print(f"调试信息: 搜索路径为 {selected_directory}")
    results = search_files_by_keyword(selected_directory, keyword, max_depth, update_label)

    progress_window.destroy()

    if results:
        print("搜索结果如下：")
        for file_path in results:
            print(file_path)
    else:
        print("未找到符合条件的文件。")

if __name__ == "__main__":
    main()